// 屏保状态管理
let isScreenSaverActive = false;
let slideInterval = null;
let currentImageIndex = 0;
let settings = {
  blurIntensity: 10,
  slideInterval: 5000,
  backgroundStyle: 'images'
};

// 背景图片URL列表 (使用在线图片服务)
const backgroundImages = [
  'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1920&h=1080&fit=crop',
  'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=1920&h=1080&fit=crop',
  'https://images.unsplash.com/photo-1426604966848-d7adac402bff?w=1920&h=1080&fit=crop',
  'https://images.unsplash.com/photo-1501594907352-04cda38ebc29?w=1920&h=1080&fit=crop',
  'https://images.unsplash.com/photo-1472214103451-9374bd1c798e?w=1920&h=1080&fit=crop',
  'https://images.unsplash.com/photo-1469474968028-56623f02e42e?w=1920&h=1080&fit=crop',
  'https://images.unsplash.com/photo-1506197603052-3cc9c3a201bd?w=1920&h=1080&fit=crop',
  'https://images.unsplash.com/photo-1493246507139-91e8fad9978e?w=1920&h=1080&fit=crop'
];

// 渐变背景列表（带毛玻璃效果）
const gradientBackgrounds = [
  {
    gradient: 'linear-gradient(45deg, rgba(102, 126, 234, 0.85) 0%, rgba(118, 75, 162, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 30% 70%, rgba(255, 255, 255, 0.1) 0%, transparent 50%)'
  },
  {
    gradient: 'linear-gradient(45deg, rgba(240, 147, 251, 0.85) 0%, rgba(245, 87, 108, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 70% 30%, rgba(255, 255, 255, 0.15) 0%, transparent 50%)'
  },
  {
    gradient: 'linear-gradient(45deg, rgba(79, 172, 254, 0.85) 0%, rgba(0, 242, 254, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.12) 0%, transparent 50%)'
  },
  {
    gradient: 'linear-gradient(45deg, rgba(67, 233, 123, 0.85) 0%, rgba(56, 249, 215, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%)'
  },
  {
    gradient: 'linear-gradient(45deg, rgba(250, 112, 154, 0.85) 0%, rgba(254, 225, 64, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 40% 60%, rgba(255, 255, 255, 0.14) 0%, transparent 50%)'
  },
  {
    gradient: 'linear-gradient(45deg, rgba(168, 237, 234, 0.85) 0%, rgba(254, 214, 227, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 60% 40%, rgba(255, 255, 255, 0.13) 0%, transparent 50%)'
  },
  {
    gradient: 'linear-gradient(45deg, rgba(255, 154, 158, 0.85) 0%, rgba(254, 207, 239, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 25% 75%, rgba(255, 255, 255, 0.11) 0%, transparent 50%)'
  },
  {
    gradient: 'linear-gradient(45deg, rgba(255, 236, 210, 0.85) 0%, rgba(252, 182, 159, 0.85) 100%)',
    overlay: 'radial-gradient(circle at 75% 25%, rgba(255, 255, 255, 0.16) 0%, transparent 50%)'
  }
];

// 添加启动日志
console.log('屏保内容脚本已加载');

// 确保页面完全加载后再初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeScreenSaver);
} else {
  initializeScreenSaver();
}

function initializeScreenSaver() {
  console.log('屏保功能初始化完成，DOM状态:', document.readyState);
  
  // 清理可能存在的旧的屏保元素（页面刷新时）
  removeScreenSaverOverlay();
  
  // 重置状态
  isScreenSaverActive = false;
  if (slideInterval) {
    clearInterval(slideInterval);
    slideInterval = null;
  }
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log('收到消息:', request);
  
  try {
    if (request.action === 'toggleBlur') {
      console.log('开始激活屏保, 设置:', request.settings);
      settings = { ...settings, ...request.settings };
      activateScreenSaver();
      sendResponse({success: true});
    } else if (request.action === 'stopBlur') {
      console.log('停用屏保');
      deactivateScreenSaver();
      sendResponse({success: true});
    } else if (request.action === 'getState') {
      console.log('查询状态:', isScreenSaverActive);
      sendResponse({isActive: isScreenSaverActive});
    } else if (request.action === 'ping') {
      console.log('收到ping请求');
      sendResponse({
        success: true, 
        message: 'pong', 
        timestamp: Date.now(),
        readyState: document.readyState,
        url: window.location.href
      });
    } else {
      console.log('未知操作:', request.action);
      sendResponse({success: false, error: '未知操作'});
    }
  } catch (error) {
    console.error('处理消息时出错:', error);
    sendResponse({success: false, error: error.message});
  }
  
  return true; // 保持消息通道开放
});

// 激活屏保
function activateScreenSaver() {
  console.log('激活屏保函数被调用');
  
  if (isScreenSaverActive) {
    console.log('屏保已经激活，跳过');
    return;
  }
  
  console.log('开始激活屏保...');
  isScreenSaverActive = true;
  
  try {
    console.log('创建屏保覆盖层...');
    createScreenSaverOverlay();
    
    console.log('开始背景幻灯片...');
    startBackgroundSlideshow();
    
    console.log('添加事件监听器...');
    // 只添加特定的退出方式
    document.addEventListener('keydown', handleSpecificKeys);
    
    // 添加鼠标事件来阻止默认行为（但不退出屏保）
    document.addEventListener('click', preventDefaultAction, true);
    document.addEventListener('mousedown', preventDefaultAction, true);
    document.addEventListener('mouseup', preventDefaultAction, true);
    document.addEventListener('contextmenu', preventDefaultAction, true);
    document.addEventListener('wheel', preventDefaultAction, true);
    
    console.log('屏保激活完成');
  } catch (error) {
    console.error('激活屏保时出错:', error);
    isScreenSaverActive = false;
  }
}

// 停用屏保
function deactivateScreenSaver() {
  if (!isScreenSaverActive) return;
  
  isScreenSaverActive = false;
  removeScreenSaverOverlay();
  stopBackgroundSlideshow();
  
  // 移除事件监听器
  document.removeEventListener('keydown', handleSpecificKeys);
  document.removeEventListener('click', preventDefaultAction, true);
  document.removeEventListener('mousedown', preventDefaultAction, true);
  document.removeEventListener('mouseup', preventDefaultAction, true);
  document.removeEventListener('contextmenu', preventDefaultAction, true);
  document.removeEventListener('wheel', preventDefaultAction, true);
}

// 创建屏保覆盖层
function createScreenSaverOverlay() {
  console.log('创建屏保覆盖层函数被调用');
  
  // 移除可能存在的旧覆盖层
  removeScreenSaverOverlay();
  
  // 检查backdrop-filter支持
  const testDiv = document.createElement('div');
  testDiv.style.backdropFilter = 'blur(1px)';
  const supportsBackdropFilter = testDiv.style.backdropFilter !== '';
  console.log('backdrop-filter支持:', supportsBackdropFilter);
  
  // 检查webkit前缀支持
  testDiv.style.webkitBackdropFilter = 'blur(1px)';
  const supportsWebkitBackdropFilter = testDiv.style.webkitBackdropFilter !== '';
  console.log('webkit-backdrop-filter支持:', supportsWebkitBackdropFilter);
  
  // 模糊主内容
  const blurOverlay = document.createElement('div');
  blurOverlay.id = 'screen-saver-blur-overlay';
  
  let blurCSS = `
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9998 !important;
    pointer-events: none !important;
  `;
  
  // 如果支持backdrop-filter，使用模糊效果
  if (supportsBackdropFilter || supportsWebkitBackdropFilter) {
    blurCSS += `
      backdrop-filter: blur(${settings.blurIntensity}px) !important;
      -webkit-backdrop-filter: blur(${settings.blurIntensity}px) !important;
    `;
    console.log('使用backdrop-filter模糊效果');
  } else {
    // 备用方案：使用半透明白色覆盖层
    blurCSS += `
      background: rgba(255, 255, 255, 0.3) !important;
    `;
    console.log('使用备用半透明覆盖层');
  }
  
  blurOverlay.style.cssText = blurCSS;
  console.log('模糊覆盖层已创建');
  
  // 背景层
  const backgroundOverlay = document.createElement('div');
  backgroundOverlay.id = 'screen-saver-background-overlay';
  backgroundOverlay.style.cssText = `
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9997 !important;
    transition: all 1.5s ease-in-out !important;
    pointer-events: none !important;
  `;
  
  // 毛玻璃纹理层（仅用于渐变背景）
  const glassTextureOverlay = document.createElement('div');
  glassTextureOverlay.id = 'screen-saver-glass-texture';
  glassTextureOverlay.style.cssText = `
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9997 !important;
    pointer-events: none !important;
    opacity: 0 !important;
    transition: opacity 1.5s ease-in-out !important;
    background: 
      radial-gradient(circle at 20% 50%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.05) 0%, transparent 50%),
      radial-gradient(circle at 40% 80%, rgba(255, 255, 255, 0.08) 0%, transparent 50%),
      radial-gradient(circle at 60% 30%, rgba(255, 255, 255, 0.06) 0%, transparent 50%),
      linear-gradient(45deg, 
        rgba(255, 255, 255, 0.02) 0%, 
        transparent 25%, 
        rgba(255, 255, 255, 0.03) 50%, 
        transparent 75%, 
        rgba(255, 255, 255, 0.02) 100%
      );
    background-size: 800px 800px, 600px 600px, 900px 900px, 700px 700px, 400px 400px;
    animation: glassTextureMove 20s ease-in-out infinite;
  `;
  
  // 添加动画样式
  if (!document.getElementById('glass-texture-animation-style')) {
    const style = document.createElement('style');
    style.id = 'glass-texture-animation-style';
    style.textContent = `
      @keyframes glassTextureMove {
        0%, 100% {
          background-position: 0% 0%, 100% 100%, 0% 100%, 100% 0%, 0% 0%;
        }
        25% {
          background-position: 100% 0%, 0% 100%, 100% 100%, 0% 0%, 25% 25%;
        }
        50% {
          background-position: 100% 100%, 0% 0%, 100% 0%, 0% 100%, 50% 50%;
        }
        75% {
          background-position: 0% 100%, 100% 0%, 0% 0%, 100% 100%, 75% 75%;
        }
      }
    `;
    document.head.appendChild(style);
  }
  
  // 时钟显示
  const clockDisplay = document.createElement('div');
  clockDisplay.id = 'screen-saver-clock';
  clockDisplay.style.cssText = `
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 4em;
    font-weight: 300;
    text-shadow: 2px 2px 10px rgba(0,0,0,0.5);
    z-index: 9999;
    pointer-events: none;
    text-align: center;
  `;
  
  // 添加日期显示
  const dateDisplay = document.createElement('div');
  dateDisplay.id = 'screen-saver-date';
  dateDisplay.style.cssText = `
    position: fixed;
    top: 60%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 1.5em;
    font-weight: 300;
    text-shadow: 2px 2px 10px rgba(0,0,0,0.5);
    z-index: 9999;
    pointer-events: none;
    text-align: center;
    opacity: 0.8;
  `;
  
  // 退出提示
  const exitHint = document.createElement('div');
  exitHint.id = 'screen-saver-exit-hint';
  exitHint.style.cssText = `
    position: fixed;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
    color: white;
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 1em;
    text-shadow: 2px 2px 10px rgba(0,0,0,0.5);
    z-index: 9999;
    pointer-events: none;
    text-align: center;
    opacity: 0.6;
    animation: fadeInOut 3s ease-in-out infinite;
  `;
  exitHint.textContent = '按 Esc 键、F11 键、Ctrl+Shift+S 或通过插件按钮退出屏保';
  
  // 添加CSS动画
  const style = document.createElement('style');
  style.textContent = `
    @keyframes fadeInOut {
      0%, 100% { opacity: 0.3; }
      50% { opacity: 0.8; }
    }
  `;
  document.head.appendChild(style);
  
  // 添加到页面
  console.log('开始添加DOM元素到页面...');
  
  try {
    document.body.appendChild(backgroundOverlay);
    console.log('背景覆盖层已添加');
    
    document.body.appendChild(glassTextureOverlay);
    console.log('毛玻璃纹理层已添加');
    
    document.body.appendChild(blurOverlay);
    console.log('模糊覆盖层已添加');
    
    document.body.appendChild(clockDisplay);
    console.log('时钟显示已添加');
    
    document.body.appendChild(dateDisplay);
    console.log('日期显示已添加');
    
    document.body.appendChild(exitHint);
    console.log('退出提示已添加');
    
    console.log('所有DOM元素添加完成');
  } catch (error) {
    console.error('添加DOM元素时出错:', error);
    throw error;
  }
  
  // 更新时钟
  updateClock();
  setInterval(() => {
    if (isScreenSaverActive) {
      updateClock();
    }
  }, 1000);
}

// 移除屏保覆盖层
function removeScreenSaverOverlay() {
  const overlays = [
    'screen-saver-blur-overlay',
    'screen-saver-background-overlay',
    'screen-saver-glass-texture',
    'screen-saver-clock',
    'screen-saver-date',
    'screen-saver-exit-hint'
  ];
  
  overlays.forEach(id => {
    const element = document.getElementById(id);
    if (element) {
      element.remove();
    }
  });
}

// 开始背景幻灯片
function startBackgroundSlideshow() {
  updateBackground();
  slideInterval = setInterval(updateBackground, settings.slideInterval);
}

// 停止背景幻灯片
function stopBackgroundSlideshow() {
  if (slideInterval) {
    clearInterval(slideInterval);
    slideInterval = null;
  }
}

// 更新背景
function updateBackground() {
  const backgroundOverlay = document.getElementById('screen-saver-background-overlay');
  const glassTextureOverlay = document.getElementById('screen-saver-glass-texture');
  
  if (!backgroundOverlay) return;
  
  if (settings.backgroundStyle === 'images') {
    // 图片背景模式
    const imageUrl = backgroundImages[currentImageIndex];
    backgroundOverlay.style.background = `url(${imageUrl}) center/cover no-repeat`;
    backgroundOverlay.style.backdropFilter = 'blur(2px)';
    backgroundOverlay.style.webkitBackdropFilter = 'blur(2px)';
    backgroundOverlay.style.border = 'none';
    backgroundOverlay.style.boxShadow = 'none';
    
    // 隐藏毛玻璃纹理层
    if (glassTextureOverlay) {
      glassTextureOverlay.style.opacity = '0';
    }
    
    currentImageIndex = (currentImageIndex + 1) % backgroundImages.length;
  } else {
    // 渐变背景模式 - 毛玻璃效果
    const gradientData = gradientBackgrounds[currentImageIndex];
    
    // 应用毛玻璃效果的渐变背景
    backgroundOverlay.style.background = `
      ${gradientData.overlay}, 
      ${gradientData.gradient}
    `;
    
    // 添加毛玻璃效果
    backgroundOverlay.style.backdropFilter = 'blur(20px) saturate(1.8) brightness(1.2)';
    backgroundOverlay.style.webkitBackdropFilter = 'blur(20px) saturate(1.8) brightness(1.2)';
    
    // 添加边框和阴影效果
    backgroundOverlay.style.border = '1px solid rgba(255, 255, 255, 0.18)';
    backgroundOverlay.style.boxShadow = `
      0 8px 32px rgba(0, 0, 0, 0.3),
      inset 0 1px 0 rgba(255, 255, 255, 0.2),
      inset 0 -1px 0 rgba(255, 255, 255, 0.1)
    `;
    
    // 显示并更新毛玻璃纹理层
    if (glassTextureOverlay) {
      glassTextureOverlay.style.opacity = '1';
      
      // 为每个渐变添加不同的纹理动画延迟
      const animationDelay = (currentImageIndex * 2.5) + 's';
      glassTextureOverlay.style.animationDelay = animationDelay;
    }
    
    currentImageIndex = (currentImageIndex + 1) % gradientBackgrounds.length;
  }
}

// 更新时钟
function updateClock() {
  const clockElement = document.getElementById('screen-saver-clock');
  const dateElement = document.getElementById('screen-saver-date');
  
  if (clockElement && dateElement) {
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
    
    const dateString = now.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    });
    
    clockElement.textContent = timeString;
    dateElement.textContent = dateString;
  }
}

// 处理特定按键
function handleSpecificKeys(event) {
  if (!isScreenSaverActive) return;
  
  // 只允许特定按键退出屏保
  const allowedKeys = [
    'Escape',           // Esc键
    'F11',              // F11键（常用于退出全屏）
  ];
  
  // 允许特定组合键
  const isAllowedCombo = (
    (event.ctrlKey && event.shiftKey && event.key === 'S') ||  // Ctrl+Shift+S (我们的切换快捷键)
    (event.metaKey && event.shiftKey && event.key === 'S') ||  // Cmd+Shift+S (Mac版本)
    (event.altKey && event.key === 'F4')                       // Alt+F4 (关闭窗口)
  );
  
  if (allowedKeys.includes(event.key) || isAllowedCombo) {
    console.log('检测到允许的退出按键:', event.key);
    event.preventDefault();
    event.stopPropagation();
    deactivateScreenSaver();
  } else {
    // 阻止其他按键的默认行为，但不退出屏保
    event.preventDefault();
    event.stopPropagation();
    console.log('按键被阻止，但不退出屏保:', event.key);
  }
}

// 阻止默认鼠标行为（但不退出屏保）
function preventDefaultAction(event) {
  if (!isScreenSaverActive) return;
  
  event.preventDefault();
  event.stopPropagation();
  
  // 可以添加一些视觉反馈，比如点击时的涟漪效果
  if (event.type === 'click') {
    console.log('鼠标点击被阻止，屏保继续运行');
    // 可以在这里添加一些视觉效果来提示用户
    showClickFeedback(event.clientX, event.clientY);
  }
}

// 显示点击反馈效果
function showClickFeedback(x, y) {
  const ripple = document.createElement('div');
  ripple.style.cssText = `
    position: fixed !important;
    top: ${y - 20}px !important;
    left: ${x - 20}px !important;
    width: 40px !important;
    height: 40px !important;
    border: 2px solid rgba(255, 255, 255, 0.6) !important;
    border-radius: 50% !important;
    z-index: 10000 !important;
    pointer-events: none !important;
    animation: rippleEffect 0.6s ease-out forwards !important;
  `;
  
  // 添加动画样式（如果还没有）
  if (!document.getElementById('ripple-animation-style')) {
    const style = document.createElement('style');
    style.id = 'ripple-animation-style';
    style.textContent = `
      @keyframes rippleEffect {
        0% {
          transform: scale(0);
          opacity: 1;
        }
        100% {
          transform: scale(3);
          opacity: 0;
        }
      }
    `;
    document.head.appendChild(style);
  }
  
  document.body.appendChild(ripple);
  
  // 0.6秒后移除涟漪效果
  setTimeout(() => {
    if (ripple && ripple.parentNode) {
      ripple.remove();
    }
  }, 600);
}

// 监听页面卸载，清理资源
window.addEventListener('beforeunload', function() {
  deactivateScreenSaver();
}); 